package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.ai.domain.SysAiQuest;
import com.ruoyi.ai.domain.SysAiTasks;
import com.ruoyi.ai.domain.SysAiTodo;
import com.ruoyi.ai.service.ISysAiQuestService;
import com.ruoyi.ai.service.ISysAiTasksService;
import com.ruoyi.ai.service.ISysAiTodoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysAITask;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysAIService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysAIServiceImpl;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * swagger 用户测试方法
 *
 * @author ruoyi
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/ai/assistant")
public class AIController extends BaseController
{
    @Autowired
    private ISysAiTasksService sysAiTasksService;

    @Autowired
    private ISysAiTodoService sysAiTodoService;

    @Autowired
    private ISysAiQuestService sysAiQuestService;


    //@Autowired
    private ISysAIService sysAIService = new SysAIServiceImpl();

    private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();
    {
        users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
        users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
    }

    private final static Map<Integer, AITaskEntity> tasks = new LinkedHashMap<Integer, AITaskEntity>();
    {
        try {
            tasks.put(1, new AITaskEntity(1, "产品会议", "产品讨论", Arrays.asList(new String[]{"sisi", "老姚"}), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2024-06-14 17:00:00")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            tasks.put(2, new AITaskEntity(2, "开发会议", "开发讨论", Arrays.asList(new String[]{"sisi", "张亮"}), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2024-06-13 14:00:00")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("AI任务语义分析")
    @PostMapping("/task_analysis")
    public R<List<SysAiTasks>> task_analysis(@RequestBody AIContentEntity content) throws Exception {
        //List<AITaskEntity> taskList = new ArrayList<AITaskEntity>(tasks.values());
        logger.info("=========sysAIService===========");
        logger.info(JSON.toJSONString(sysAIService));

        return R.ok(sysAIService.taskAnalysis(content.getContent()));
    }

    @ApiOperation("语言大模型聊天")
    @PostMapping("/chat")
    public R<String> chat(@RequestBody AIContentEntity content) throws Exception {
        return R.ok(sysAIService.chat(content.getContent()));
    }

    /**
     * 查询AI任务列表
     */
    @ApiOperation("查询AI任务列表")
    @GetMapping("/task_list")
    public TableDataInfo list(SysAiTasks sysAiTasks)
    {
        System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasks));
        List<SysAiTasks> list = sysAiTasksService.selectSysAiTasksListWithNoNull(sysAiTasks);
        return getDataTable(list);
    }

    public String cleanStr(String content){
        if(content != null){
            if(content.equals("无")){
                return "";
            }
            if(content.equals("[]")){
                return "";
            }
        }
        return content;
    }

    public String splitJson(String content){
        //content = "[{\"行动项\":\"参加产品会\"}]";
        String result = "";
        try {
            JSONArray jsonArray = JSONArray.parseArray(content);
            for (int i=0;i<jsonArray.size();i++){
                try {
                    JSONObject jsonChatdata = JSONObject.parseObject(jsonArray.get(i).toString());
                    result = result + "◆" + jsonChatdata.getString("行动项") + "\n";
                }catch (Exception ex3){
                    result = result + "◆" + jsonArray.get(i).toString() + "\n";
                }
            }

        }catch (Exception ex1){

            try {
                JSONObject jsonChatdata = JSONObject.parseObject(content);
                result = result + "◆" + jsonChatdata.getString("行动项") + "\n";

            }catch (Exception ex2) {
                result = content;
            }
        }

        return result;
    }


    /**
     * 查询AI todo列表
     */
    @ApiOperation("查询AI todo列表")
    @GetMapping("/todo_list")
    public TableDataInfo todolist(SysAiTodo sysAiTodo)
    {
        startPage();
        /*
        Map<String, Object> params =  sysAiTodo.getParams();
        if(!"".equals((String)params.get("beginMsgtime")) && params.get("beginMsgtime")!=null){
            String dateString = (String)params.get("beginMsgtime") + " 00:00:00";
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(dateString);
                //Timestamp timestamp = new Timestamp(date.getTime());
                params.replace("beginMsgtime", Long.toString(date.getTime()));
                System.out.println(date.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if(!"".equals((String)params.get("endMsgtime")) && params.get("endMsgtime")!=null){
            String dateString = (String)params.get("endMsgtime") + " 23:59:59";
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(dateString);
                //Timestamp timestamp = new Timestamp(date.getTime());
                params.replace("endMsgtime", Long.toString(date.getTime()));
                System.out.println(date.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        sysAiTodo.setParams(params);*/
        //SysUser user = SecurityUtils.getLoginUser().getUser();
        //sysAiTasks.setOrignalMsg(user.getRemark());
        //sysAiTasks.setTaskOwner(user.getRemark());
        System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTodo));
        List<SysAiTodo> list = sysAiTodoService.selectSysAiTodoList(sysAiTodo);
        return getDataTable(list);
    }


    /**
     * 获取AI任务详细信息
     */
    @ApiOperation("获取AI任务详细信息")
    @GetMapping(value = "/task/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysAiTasksService.selectSysAiTasksById(id));
    }

    /**
     * 修改AI任务
     */
    @ApiOperation("修改AI任务")
    @PostMapping("/task")
    public AjaxResult edit(@RequestBody SysAiTasks sysAiTasks)
    {
        sysAiTasks.setIsEdit(1);//设置为 已编辑过
        return toAjax(sysAiTasksService.updateSysAiTasks(sysAiTasks));
    }

    /**
     * 获取AI待办详细信息
     */
    @ApiOperation("获取AITodo详细信息")
    @GetMapping(value = "todo/{id}")
    public AjaxResult getTodoInfo(@PathVariable("id") Long id)
    {
        return success(sysAiTodoService.selectSysAiTodoById(id));
    }

    /**
     * 新增AI待办
     */
    @ApiOperation("新增AITodo详细信息")
    @Log(title = "AI待办", businessType = BusinessType.INSERT)
    @PostMapping("/todo/add")
    public AjaxResult addTodo(@RequestBody SysAiTodo sysAiTodo)
    {
        return toAjax(sysAiTodoService.insertSysAiTodo(sysAiTodo));
    }

    /**
     * 修改AI待办
     */
    @ApiOperation("修改AITodo详细信息")
    @PostMapping("/todo/edit")
    public AjaxResult editTodo(@RequestBody SysAiTodo sysAiTodo)
    {
        return toAjax(sysAiTodoService.updateSysAiTodo(sysAiTodo));
    }

    /**
     * 删除AI待办
     */
    @ApiOperation("删除AITodo详细信息")
    @DeleteMapping("/todo/delete/{ids}")
    public AjaxResult removeTodo(@PathVariable Long[] ids)
    {
        return toAjax(sysAiTodoService.deleteSysAiTodoByIds(ids));
    }

    /**
     * 删除AI待办
     */
    @ApiOperation("获取 quest 列表")
    @GetMapping("/quest/list")
    public TableDataInfo list(SysAiQuest sysAiQuest)
    {
        List<SysAiQuest> list = sysAiQuestService.selectSysAiQuestList(sysAiQuest);
        return getDataTable(list);
    }

    /**
     * AI任务_企业微信加入日历
     */
    @ApiOperation("AI任务_企业微信加入日历")
    @PostMapping("/task/addQYWXSchedule")
    public AjaxResult addQYWXSchedule(@RequestBody SysAiTasks sysAiTasks) throws IOException, ParseException {
        sysAiTasks.setIsEdit(1);//设置为 已编辑过
        sysAiTasksService.updateSysAiTasks(sysAiTasks);

        String access_token = SysAIServiceImpl.getQYWXAccessToken();
        //创建日程
        SysAIServiceImpl.addQYWXSchedule(sysAiTasks, access_token, sysAiTasks.getTaskOwner());

        return toAjax(1);
    }

    /**
     * 删除AI任务
     */
    @ApiOperation("删除AI任务")
    @DeleteMapping("/task/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysAiTasksService.deleteSysAiTasksByIds(ids));
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public R<List<UserEntity>> userList()
    {
        List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
        return R.ok(userList);
    }

    @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
    @GetMapping("/user/{userId}")
    public R<UserEntity> getUser(@PathVariable Integer userId)
    {
        if (!users.isEmpty() && users.containsKey(userId))
        {
            return R.ok(users.get(userId));
        }
        else
        {
            return R.fail("用户不存在");
        }
    }

    @ApiOperation("新增用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
        @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping("/save")
    public R<String> save(UserEntity user)
    {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
        {
            return R.fail("用户ID不能为空");
        }
        users.put(user.getUserId(), user);
        return R.ok();
    }

    @ApiOperation("更新用户")
    @PutMapping("/update")
    public R<String> update(@RequestBody UserEntity user)
    {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
        {
            return R.fail("用户ID不能为空");
        }
        if (users.isEmpty() || !users.containsKey(user.getUserId()))
        {
            return R.fail("用户不存在");
        }
        users.remove(user.getUserId());
        users.put(user.getUserId(), user);
        return R.ok();
    }

    @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
    @DeleteMapping("/user/{userId}")
    public R<String> delete(@PathVariable Integer userId)
    {
        if (!users.isEmpty() && users.containsKey(userId))
        {
            users.remove(userId);
            return R.ok();
        }
        else
        {
            return R.fail("用户不存在");
        }
    }
}

@ApiModel(value = "AIContentEntity", description = "任务语义分析实体")
class AIContentEntity
{
    @ApiModelProperty("聊天内容")
    private String content;

    public AIContentEntity()
    {

    }

    public String getContent()
    {
        return content;
    }

    public void setContent(String content)
    {
        this.content = content;
    }

}

@ApiModel(value = "AITaskEntity", description = "任务语义分析实体")
class AITaskEntity
{
    @ApiModelProperty("ID")
    private Integer Id;

    @ApiModelProperty("任务名称")
    private String taskname;

    @ApiModelProperty("主要议题")
    private String taskmemo;

    @ApiModelProperty("相关人员")
    private List<String> userlist;

    @ApiModelProperty("任务时间")
    private Date taskdate;

    public AITaskEntity()
    {

    }

    public AITaskEntity(Integer Id, String taskname, String taskmemo, List<String> userlist, Date taskdate)
    {
        this.Id = Id;
        this.taskname = taskname;
        this.taskmemo = taskmemo;
        this.userlist = userlist;
        this.taskdate = taskdate;
    }

    public Integer getId()
    {
        return Id;
    }

    public void setId(Integer id)
    {
        this.Id = id;
    }

    public String getTaskname()
    {
        return taskname;
    }

    public void setTaskname(String taskname)
    {
        this.taskname = taskname;
    }

    public String getTaskmemo()
    {
        return taskmemo;
    }

    public void setTaskmemo(String taskmemo)
    {
        this.taskmemo = taskmemo;
    }

    public List<String> getUserlist()
    {
        return userlist;
    }

    public void setUserlist(List<String> userlist)
    {
        this.userlist = userlist;
    }

    public Date getTaskdate()
    {
        return taskdate;
    }

    public void setTaskdate(Date taskdate)
    {
        this.taskdate = taskdate;
    }
}
